package com.example.javagd.filter;


import com.example.javagd.constant.UrlAccessConstant;
import com.example.javagd.enums.UserPermissionType;
import com.example.javagd.util.CommonUtils;

import org.springframework.core.annotation.Order;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: springdemo
 * @description:
 * @author: hzy
 * @create: 2020-06-13 13:53
 **/
@Order(1)
@WebFilter
public class loginFilter extends CommonUtils implements Filter {

    boolean isNeedCheck(String url, UserPermissionType type){
        if (url.endsWith("/")){
            url = url.substring(0, url.length() - 1);
        }

        for (String u : UrlAccessConstant.GetUrls(type)) {
            if (url.equals(u)){
                return false;
            }else if(u.endsWith("/**") || u.endsWith("/*")){
                u = u.replace("/*", "").replace("*", "");

                // /**
                if (u.equals(""))
                    return false;
                if (u.equals(url))
                    return false;
                // /prefix/**
                if (url.length() > u.length() && url.startsWith(u) && url.charAt(u.length()) == '/'){
                    return false;
                }
            }
        }
        return true;
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;

        //从request获取用户id
        String userId = httpServletRequest.getHeader("user_id");

        //从util里面取出用户的权限
        //UserPermissionType type = userPermissionUtils.GetUserType(userId);

        //测试
        UserPermissionType type = userPermissionUtils.GetRootType();

        if (isNeedCheck(httpServletRequest.getRequestURI(), type)){
            //如果需要验证
            //判断
            //是否是本网站。不是从地址栏非法进入
            //token正确
            //否则返回登陆界面
        //    httpServletResponse.sendRedirect("/login");
        //    return ;
            if (httpServletRequest.getHeader("referer") == null
            ){
                httpServletResponse.sendRedirect("/sys/login/");
                return ;
            }
            request.setAttribute("CheckToken", true);
        }else{
            request.setAttribute("CheckToken", false);
        }
        chain.doFilter(request, response);
    }
}
